package concurrecy.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ReentrantLockChecker implements Runnable {
    private Lock lock;

    private int count = 0;

    public ReentrantLockChecker(Lock lock) {
        this.lock = lock;
    }

    @Override
    public String toString() {
        return Thread.currentThread().getName();
    }

    public void test() {
        lock.lock();
        System.out.println(this + " 加锁 " + count);
        try {
            if(++ count == 3)
                return;
            test();
        } finally {
            lock.unlock();
            System.out.println(this + " 释放锁 " +  -- count);
        }
    }

    @Override
    public void run() {
        test();
    }
}

class MyReentrantLock extends MyLock {
    @Override
    public boolean tryLock() {
        // 没有抢到锁，但当前线程已经占有此锁了。直接获取锁
        if(super.tryLock()) {
            return true;
        } else if(owner == Thread.currentThread()) {
            state.incrementAndGet();
            return true;
        }
        return false;
    }
}

/**
 * 重入锁
 */
public class MyLockDemo2 {
    public static void main(String[] args) {
        Lock lock = new MyReentrantLock();

        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new ReentrantLockChecker(lock));
        service.execute(new ReentrantLockChecker(lock));
        service.execute(new ReentrantLockChecker(lock));

        service.shutdown();
    }
}
